package com.haifeng.questionbankcrud;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.fxml.JavaFXBuilderFactory;
import javafx.scene.Scene;
import javafx.stage.Stage;

import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Level;
import java.util.logging.Logger;


public class HelloApplication extends Application {
    private static final Logger logger = Logger.getLogger(HelloApplication.class.getName());
    private Stage mainStage;

    @Override
    public void start(Stage primaryStage) throws IOException {
//        FXMLLoader fxmlLoader = new FXMLLoader(HelloApplication.class.getResource("main-view.fxml"));
//        Scene scene = new Scene(fxmlLoader.load(), 600, 400);
        mainStage=primaryStage;
        primaryStage.setTitle("题库系统");
        gotoLogin();
//        stage.setScene(scene);
        primaryStage.show();

    }

    public void gotoLogin() {
        try {
            LoginController login = (LoginController) replaceSceneContent("login-view.fxml");
            System.out.println("次出执行");

            login.setHelloApplication(HelloApplication.this);
        } catch (Exception ex) {
            logger.log(Level.SEVERE, null, ex);
        }
    }

    /**
     * 跳转到主界面
     */
    public void gotoMain() {
        try {
            SingleChoiceController main = (SingleChoiceController) replaceSceneContent("main-view.fxml");
            main.setHelloApplication(this);
        } catch (Exception ex) {
            logger.log(Level.SEVERE, null, ex);
        }
    }

    /**
     * 替换场景
     * @param fxml
     * @return
     * @throws Exception
     */
    private Initializable replaceSceneContent(String fxml) throws Exception {

        FXMLLoader loader = new FXMLLoader();
        InputStream in = HelloApplication.class.getResourceAsStream(fxml);
        loader.setBuilderFactory(new JavaFXBuilderFactory());
        loader.setLocation(HelloApplication.class.getResource(fxml));

        try {
//            AnchorPane page = (AnchorPane) loader.load(in);
//            Scene scene = new Scene(page, 600,400);
            Scene scene = new Scene(loader.load(in), 600,400);
            mainStage.setScene(scene);
            mainStage.sizeToScene();
        } catch (Exception e) {
            logger.log(Level.SEVERE, "页面加载异常！");
        } finally {
            in.close();
        }
        return (Initializable) loader.getController();
    }



    public static void main(String[] args) {
        launch();
    }
}